;(function(window, Zepto) {

    Date.prototype.Format = function(fmt){
      var o = {
        "M+" : this.getMonth()+1,                 //月份
        "d+" : this.getDate(),                    //日
        "h+" : this.getHours(),                   //小时
        "m+" : this.getMinutes(),                 //分
        "s+" : this.getSeconds(),                 //秒
        "q+" : Math.floor((this.getMonth()+3)/3), //季度
        "S"  : this.getMilliseconds()             //毫秒
      };
      if(/(y+)/.test(fmt))
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
      for(var k in o)
        if(new RegExp("("+ k +")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
      return fmt;
   };

    function UIBase( options ) {

        var el = document.createElement( options.tagName || 'div' );
        el.className = options.className;

        if( options.appendToBody !== false ){
            this.el = document.body.appendChild( el )
        }
        else{
            this.el = el;
        }

        this.$el = $(el);
    };

    var UIBasePt = UIBase.prototype;
    UIBasePt.show = UIBasePt._show = function( ){
        this.$el.show();
    };
    UIBasePt.hide = UIBasePt._hide = function(){
        this.$el.hide();
    };
    UIBasePt.setHtml = function( html ){
        this.el.innerHTML = html;
    };
    UIBasePt.find = function( selector ){
        return this.el.querySelector( selector );
    }
    UIBasePt.destroy = function(){
        this.$el.remove();
        this.$el = this.el = null;
    }

    // Used for inheritance
    UIBase.extend = function( subclass ){

        // copy instance member
        $.extend( subclass.prototype, this.prototype, { $super: this } );
        // copy static member
        $.extend( subclass, this );

        return subclass;
    };

    // 单例模式下获取唯一实例
    UIBase.getInstance = function(){

        if( !this._instance ){
            this._instance = new this;
        }

        return this._instance;
    }

    function Mask( options ) {

        this.$super( { className: 'ui-mask' } );
    };

    UIBase.extend( Mask );

    var MaskPt = Mask.prototype;

    /*
    var options = {
        type: 'lighter', // 白色透明背景 'light'、'lighter'
        touchHide:true, // 触摸隐藏
        noTouch: true // 阻止TouchMove事件,
        callback: touchHide = true 时的隐藏回调
    }*/

    MaskPt.show = function( options ){

        var options = options || {},
            self = this;

        // restore default;
        this.el.className = 'ui-mask';

        // 透明遮罩层
        if( options.type ){
           this.el.className += ' ' + options.type
        }

        // 点击隐藏
        this.el.onclick = options.touchHide?function(){
            self.hide(); // hide方法必须在calback之前调用， 因为mask是公用的，callback 可能会使用
            options.callback&&options.callback();
            return false;
        }:null;

        this.el.ontouchmove = options.noTouch?function(){
            return false;
        }: null;

        this._show();
    }

    function Toast( options ) {
        this.$super( { className: 'ui-toast' } );
        this._mask = Mask.getInstance();
    };

    UIBase.extend( Toast );

    var ToastPt = Toast.prototype;

    // 重写show方法
    ToastPt.show = function( msg, interval, callback ){

        var self = this;
        // 避免上一次弹出的Tast的timer隐藏后续弹出的
        if( this.timer ){ clearTimeout( this.timer ); }

        var cb = function(){
            callback && callback();
            self.hide();
            self._mask.hide();
        }

        this.timer = setTimeout(cb, (interval || 2) * 1000);
        this.setHtml( msg );

        this._mask.show({
            type: 'light',
            touchHide: true,
            callback: cb
        });

        this._show();
    };

    ToastPt.hide = function(){
        this._hide();
        clearTimeout(this.timer);
        this.timer = 0;// 这一句要放在clearTimeout 后面
    }



    function Loading( options ){

        this.$super( { className: 'ui-loading' } );

        this.setHtml('<i></i><p></p>');
        this.mesage = this.find('p');

        this._mask = Mask.getInstance();
    }

    UIBase.extend( Loading );

    var LoadingPt = Loading.prototype;

    LoadingPt.show = function( msg, options ){

        this.mesage.innerHTML  = msg || '加载中' ;
        if( !options || options.needMask !== false ){
            this._mask.show({type:'lighter'});//白色透明背景
        }

        this._show();
    };

    LoadingPt.hide = function(){
        this._hide();
        this._mask.hide();
    }

// if ('function' == typeof define && define.amd) {
//   define(Controller);
// }
  function loadMainScence() {

   function Score(num) {
     this.arrScore = [];
   }
   var ScorePt = Score.prototype;
   ScorePt.setScore = function(index,score) {
     this.arrScore[index] = score;
   }
   ScorePt.pushScore = function(score) {
     this.arrScore.push(score);
   }
   ScorePt.getScore = function() {
     return this.arrScore;
   }
   ScorePt.cleanUp = function() {
     this.arrScore = [];
   }

    var toast = new Toast();
    var arrScore = new Score();
    var onceTimer = false;
    var flagClickTimer = false;
    // var flagSelected = false;
    var optionsScore = [[10,5,0],[10,5,0],[10,0,5],[10,5,0],[5,0,10]];
    function getTotalScore(options,scores,length) {
      var score = 0;
      var len = length || scores.length;
      for(var i = 0;i<len;i++){
        score += ~~options[i][--scores[i]];
      }
      console.log(score);
      return score;
    }
    function testResult(score) {
      if(score >= 35){
        return ['你患有重度加班综合症。具体表现为平日里眼神无光，仔细观察其瞳孔便可看到整个宇宙。外号：不加班浑身就不舒服斯基。此种情况无法治疗，你开心就好！','冰水浇头x2＋掌掴x10＋究极过肩摔x1 <br>每日两次，半个疗程。包好。'];
      }else if(score >=20){
        return ['你患有中度加班综合症。具体表现为不修边幅满脸是油，劲椎错位，发际线升高，肠胃崩溃张嘴口臭地图炮，肚腩呈“一波三折”状。如不立即治疗，有寿命减半、卖相对折之趋势。','健康饮食，杜绝暴饮暴食和垃圾食品。<br>保证睡眠，调整情绪，常去户外走一走。'];
      }else{
        return ['你患有轻度加班综合症。具体表现为记忆力下降、智商不稳定、老板问话偶尔蒙逼等症状。如不趁早治疗，其加重趋势约为99.99％','加班时需多看美女同事，以舒缓精神压力为主。<br>若无资源也可用"新建文件夹"中的内容代替。'];
      }
    }
    var qaSelected = false;
    var $terminal = $('body').attr('data-view');
    var $views = $('.view');
    var $switch_music = $('#switch_music');
    var $tableID = $('#JsTableID');
    var $tableDate = $('#JsTableDate');
    var $tableP1 = $('#JsTableP1');
    var $tableP2 = $('#JsTableP2');
    var $qa = $('.qa');
    var $qalist = $qa.find('li');
    var game = {
      restart: function() {
        arrScore.cleanUp();
        // console.log(arrScore.getScore());
        $tableP1.html('');
        $tableP2.html('');
        // $qa.removeClass('checked');
        qaSelected = false;
        $qalist.removeClass('selected');
        $views.eq(0).addClass('startAni');
        $views.last().removeClass('startAni');
      },
      gotoEnd: function() {
        // alert($terminal);
        var adr = '/open/activity/overtime/ticketList';
        if ($terminal=='alipay'){
          window.location.href = baseUrl+adr;
          return;
        }
        $('.view7').hide();
      }
    }
    var $restart = $('#JsRestart').on('click',function() {
      // console.log(flagClickTimer);
      onceTimer = false;
      flagClickTimer = false;
      clickTimer();
      game.restart();
    });
    var $gotoEnd = $('#JsGotoEnd').on('click',function() {

      game.gotoEnd();
    });
    function clickTimer() {
      if(!onceTimer){
        onceTimer = true;
        setTimeout(function() {
          flagClickTimer = true;
          onceTimer = false;
        },1500);
      }
    }
    clickTimer();
    $views.eq(0).find('select').on('click',function(event) {
      event.stopPropagation();
    });
    $views.each(function(i,item) {
      var $self = $(this);
      var index = i-1;
      // $self.find('.aniEnd').last().on('animationEnd webkitAnimationEnd',function() {
        $self.on('click',function() {
          if(flagClickTimer){
            flagClickTimer = false;
            // console.log('click success');
            $switch_music.hide();
            $self.addClass('showForm');
            qaSelected = false;
            var $qa = $self.find('.qa').on('click','li',function(e) {
              // $($qa).addClass('checked');
              $(this).siblings('li').removeClass('selected');
              $(this).addClass('selected');
              // flagSelected = true;
              arrScore.setScore(index,$(this).attr('data-v'));
            });
            $self.find('.areabtn').on('click',function(event) {
              event.stopPropagation();
              // console.log('clickTimer');
              var $lis = $self.find('.qa li');
              $lis.each(function(i,item) {
                if($(this).hasClass('selected')){
                  qaSelected = true;
                }
              })
              if($lis.length && !qaSelected){
                toast.show('请点击选项');
                return false;
              }

              if($self.index() == $views.length){
                // console.log('last view');
                var arrText = testResult(getTotalScore(optionsScore,arrScore.getScore()));
                var d = new Date().Format('yyyy-MM-dd');
                // $tableID.html('');
                $tableDate.html(d);
                $tableP1.html(arrText[0]);
                $tableP2.html(arrText[1]);
              }

              // flagSelected = false;
              $self.removeClass('showForm');
              // $self.hide();
              $self.removeClass('startAni')
              $self.next().addClass('startAni');
              // alert($self.next());
              $switch_music.show();
              // console.log(arrScore.getScore());
              clickTimer();

            })
          }
        })
      // })
    });
    $switch_music.on('click',function(event) {
      event.stopPropagation();
      $(this).toggleClass('on');
      if($(this).hasClass('on')){
        $(this).find('audio').get(0).play();
      }else{
        $(this).find('audio').get(0).pause();
      }
    });
    $('#loader').hide();
    $('#container').show();
  }

  ImgPreloader(function() {
    var reg1 = /([0-9]+\.[0-9]{2})[0-9]*/;
    if (arguments[0].percentage == 1) {
      $('#loader .text').html('100%');
      window.setTimeout(loadMainScence, 200);
      AddAnalysis();

      // if(window.ZAIAppJSInterface){
      //     window.ZAIAppJSInterface.showAppLocalProgress(false);
      // }
      return;
    }
    var per = arguments[0].percentage + '';
    var pernum = ~~(per.replace(reg1, "$1") * 100);
    $('#loader .text').html(pernum + '%');
  });

  // var appShareCallback = function() {
  //   // alert('smashegg appshare callback');
  //   // console.log(arguments[0].channel);
  //   $.ajax({
  //     type: 'POST',
  //     url: '/common/MobileActivity/shareZjd.json',
  //     // url: '/common/MobileActivity/queryNumZjdGoldEgg.json ',
  //     dataType: 'json',
  //     data: {
  //       campaignId: '10002'
  //     },
  //     success: function(data) {
  //       // alert(typeof data.status);
  //
  //       if (data.status == true && data.num > 0) {
  //         //do rest
  //         draw.resetGame(resetGameCallback);
  //         // alert('do resetGameCallback2');
  //       }
  //     },
  //     error: function(xhr, type) {
  //       alert('网络异常!');
  //     }
  //   });
  //
  //   return true;
  // };
  // if (window.ZAIAppJSInterface) {
  //   //关闭 app loading toast
  //   window.ZAIAppJSInterface.showAppLocalProgress(false);
  // }

  // 分享配置，是否开启debug模式
  // window._za_share_debug_ = false;
  // var za_share_data = {
  //   link: window.baseUrl + '/open/product/activity/ProductDetail10002?channelId=8&version=2',
  //   title: '',
  //   richTitle: '',
  //   desc: '',
  //   imgUrl: 'http://static.zhongan.com/website/other/html/smashegg/share.png',
  //   // appshareClick: appShareCallback,
  //   // success: appShareCallback
  // };
  //
  // window.Zero.share(za_share_data, {
  //   type: '2,3'
  // });

})(window, $);
